package com.kstech.ks_gaz01.fragments

import android.view.MotionEvent
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.kstech.ks_gaz01.XML_ADDRESS_SENSOR_SUCCESS
import com.kstech.ks_gaz01.XML_ADDRESS_SETTING_BUTTON
import com.kstech.ks_gaz01.databinding.FragmentGch10SensorsettingBinding
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew

/**
 * author: blankii
 * created on: 2024/11/8 16:42
 * description:
 */
class GCH10SensorSettingFragment :
    BaseBindingFragment<FragmentGch10SensorsettingBinding>(FragmentGch10SensorsettingBinding::inflate),
    SocketFragmentListener {
    private var setSuccessTag = false
    private var setSuccessCount = 0
    override fun onCreateInit() {

    }

    override fun onInitView() {
        SocketManagerNew.subscribeSocketFragmentListener(this)
        binding.button1.setOnTouchListener { view, motionEvent ->
            when (motionEvent.action) {
                MotionEvent.ACTION_DOWN -> {
                    "开始标定".showSnackBar()
                    setSuccessCount = 0
                    setSuccessTag = false
                    /**
                     * 标定
                     */
                    SocketManagerNew.sendWriteMsg(XML_ADDRESS_SETTING_BUTTON, "170")
                    /**
                     * 读取一下 读取是否标定成功
                     */
                    SocketManagerNew.addReadyLooperList(
                        true, arrayListOf(
                            SocketManagerNew.ReadBean(
                                XML_ADDRESS_SENSOR_SUCCESS
                            )
                        )
                    )
                }

                MotionEvent.ACTION_UP -> {
                    SocketManagerNew.sendWriteMsg(XML_ADDRESS_SETTING_BUTTON, "0")
                }
            }
            true
        }
    }

    override fun writeSuccess(address: String, value: String) {

    }

    override fun readSuccess(address: String, result: ArrayList<String>) {
        /**
         * XML_ADDRESS_SENSOR_SUCCESS 标定成功返回0055
         * 但是控制器标定成功需要一定时间设成0055，所以需要循环的读取
         * 0055 停留一段时间就会重新置成0，所以加了setSuccessTag
         */
        if (address == XML_ADDRESS_SENSOR_SUCCESS) {
            if (setSuccessTag) {
                return
            }
            if (!setSuccessTag && setSuccessCount < 20 && result[0] == "0055") {
                setSuccessTag = true
                SocketManagerNew.clearReadList()
                "传感器标定成功".showSnackBar()
            } else if (setSuccessCount >= 20 && !setSuccessTag) {
                "传感器标定失败".showSnackBar()
                SocketManagerNew.clearReadList()
            } else {
                "正在请求传感器标定结果:${setSuccessCount}次".showSnackBar()
            }
            setSuccessCount++
        }
    }
}